import { ValidationPipe } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { NestFactory } from '@nestjs/core'
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'
import { AppModule } from './app.module'
import { ExceptionsFilter } from './common/filters/exceptions-filter'
import { HttpExceptionsFilter } from './common/filters/http-exceptions-filter'

async function bootstrap() {
  const app = await NestFactory.create(AppModule)
  const config = app.get(ConfigService)
  const port = config.get<number>('app.port') || 8080
  // 设置 api 访问前缀
  const prefix = config.get<string>('app.prefix')

  // 往 app 上添加管道操作
  // 全局验证
  app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true }))
  // 全局过滤
  app.useGlobalFilters(new ExceptionsFilter())
  app.useGlobalFilters(new HttpExceptionsFilter())

  const swaggerOptions = new DocumentBuilder()
    .setTitle('xxx 管理系统')
    .setDescription('xxx 文档')
    .setVersion('2.0')
    .addBearerAuth()
    .build()
  const documentServer = SwaggerModule.createDocument(app, swaggerOptions)

  SwaggerModule.setup(`${prefix}/swagger-ui`, app, documentServer, {
    swaggerOptions: {
      persistAuthorization: true
    },
    customSiteTitle: 'API Docs'
  })

  await app.listen(port)

  console.log(
    `xxx 服务启动成功 `,
    '\n',
    '\n',
    '服务地址',
    `http://localhost:${port}${prefix}/`,
    '\n',
    'swagger 文档地址        ',
    `http://localhost:${port}${prefix}/swagger-ui/`
  )
}
bootstrap()
